Spring Security | Note-12

Spring Security Note-12


退出登录

如何退出登录

退出登录,需要访问一个特定的服务,默认情况下,服务的路径是/logout;

并且退出成功后跳转的URL是登录URL + ?logout的路径;

Spring Security默认的退出处理逻辑

使当前session失效;

清除与当前用户相关的remember-me记录;

清空当前的SecurityContext;

重定向到登录页;

与退出登录相关的配置
自定义成功退出的逻辑处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ImoocLogoutSuccessHandler implements LogoutSuccessHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
private String signOutUrl;
private ObjectMapper objectMapper = new ObjectMapper();

public ImoocLogoutSuccessHandler(String signOutUrl) {
this.signOutUrl = signOutUrl;
}

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
logger.info("退出成功");
// 自定义退出成功的逻辑
if (StringUtils.isBlank(signOutUrl)) {
// 无页面,返回JSON
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse("退出成功")));
} else {
response.sendRedirect(signOutUrl);
}
}
}
注入Bean
1
2
3
4
5
6
7
8
9
10
@Configuration
public class BrowserSecurityBeanConfig {
@Autowired
private SecurityProperties securityProperties;
@Bean
@ConditionalOnMissingBean(LogoutSuccessHandler.class)
public LogoutSuccessHandler logoutSuccessHandler(){
return new ImoocLogoutSuccessHandler(securityProperties.getBrowser().getSignOutUrl());
}
}
BrowserProperties配置URL
1
2
3
public class BrowserProperties {
private String signOutUrl = "/logout.html";
}
配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
protected void configure(HttpSecurity http) throws Exception {
applyPasswordAuthenticationConfig(http);
http.
...
// 默认
.and()
.logout().logoutUrl("/signOut")
// 成功退出的自定义URL
// .logoutSuccessUrl("/imooc-logout.html")
// 成功退出的自定义逻辑(与URL冲突)
.logoutSuccessHandler(logoutSuccessHandler)
// 删除Cookies
.deleteCookies("JSESSIONID")
.and()
// 都需要认证
...
}